package com.chj.producer_balance.backupexchange;

import cn.enjoyedu.testrabbitmq.TestProducer;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 生产者--绑定了一个备用交换器
 */
public class BackupExProducer {
    public final static String EXCHANGE_NAME = "main-exchange";
    public final static String BAK_EXCHANGE_NAME = "backup-exchange";
    public static void main(String[] argv)throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
//        connectionFactory.setVirtualHost("chj_vhost");
//        connectionFactory.setUsername("chj");
//        connectionFactory.setPassword("123456");
        // 打开连接和创建频道，与发送端一样
        Connection connection = connectionFactory.newConnection();
        final Channel channel = connection.createChannel();
        //TODO
        // 声明备用交换器
        Map<String,Object> argsMap = new HashMap<String,Object>();
        argsMap.put("alternate-exchange",BAK_EXCHANGE_NAME);
        // 主交换器
        channel.exchangeDeclare(EXCHANGE_NAME,"direct", false,false, argsMap);
        // 备用交换器
        channel.exchangeDeclare(BAK_EXCHANGE_NAME, BuiltinExchangeType.FANOUT,true,false,null);
        // 定义路由键
        String[] routekeys = {"hankin01","hankin02","hankin03"};
        for(int i=0;i<3;i++) {
            String routekey = routekeys[i % 3];
            String msg = "Hello, RabbitMQ" + (i + 1);
            //发布消息，需要参数：交换器，路由键，其中以日志消息级别为路由键
            channel.basicPublish(EXCHANGE_NAME,routekey,null,msg.getBytes());
            System.out.println("Send "+routekey+":"+msg);
        }
        channel.close();
        connection.close();
    }
}
